<?php
/**
 *
 * 版权所有：恰维网络<qwadmin.qiawei.com>
 * 作    者：寒川<hanchuan@qiawei.com>
 * 日    期：2016-01-20
 * 版    本：1.0.0
 * 功能说明：用户控制器。
 *
 **/

namespace Qwadmin\Controller;

class MemberController extends ComController
{
    public function index()
    {
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $field = isset($_GET['field']) ? $_GET['field'] : '';
        $keyword = isset($_GET['keyword']) ? htmlentities($_GET['keyword']) : '';
        $order = isset($_GET['order']) ? $_GET['order'] : 'DESC';
        $where = '';
		
        $prefix = C('DB_PREFIX');
        if ($order == 'asc') {
            $order = "{$prefix}member.t asc";
        } elseif (($order == 'desc')) {
            $order = "{$prefix}member.t desc";
        } else {
            $order = "{$prefix}member.uid asc";
        }
        if ($keyword <> '') {
            if ($field == 'user') {
                $where = "{$prefix}member.user LIKE '%$keyword%'";
            }
            if ($field == 'phone') {
                $where = "{$prefix}member.phone LIKE '%$keyword%'";
            }
            if ($field == 'qq') {
                $where = "{$prefix}member.qq LIKE '%$keyword%'";
            }
            if ($field == 'email') {
                $where = "{$prefix}member.email LIKE '%$keyword%'";
            }
        }

		
        $user = M('member');
        $pagesize = 10;#每页数量
        $offset = $pagesize * ($p - 1);//计算记录偏移量
        $count = $user->field("{$prefix}member.*,{$prefix}auth_group.id as gid,{$prefix}auth_group.title")
            ->order($order)
            ->join("{$prefix}auth_group_access ON {$prefix}member.uid = {$prefix}auth_group_access.uid")
            ->join("{$prefix}auth_group ON {$prefix}auth_group.id = {$prefix}auth_group_access.group_id")
            ->where($where)
            ->count();

        $list = $user->field("{$prefix}member.*,{$prefix}auth_group.id as gid,{$prefix}auth_group.title")
            ->order($order)
            ->join("{$prefix}auth_group_access ON {$prefix}member.uid = {$prefix}auth_group_access.uid")
            ->join("{$prefix}auth_group ON {$prefix}auth_group.id = {$prefix}auth_group_access.group_id")
            ->where($where)
            ->limit($offset . ',' . $pagesize)
            ->select();
        //$user->getLastSql();
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('page', $page);
        $group = M('auth_group')->field('id,title')->select();
        $this->assign('group', $group);
        $this->display();
    }

    public function del()
    {

        $uids = isset($_REQUEST['uids']) ? $_REQUEST['uids'] : false;
        //uid为1的禁止删除
        if ($uids == 1 or !$uids) {
            $this->error('参数错误！');
        }
        if (is_array($uids)) {
            foreach ($uids as $k => $v) {
                if ($v == 1) {//uid为1的禁止删除
                    unset($uids[$k]);
                }
                $uids[$k] = intval($v);
            }
            if (!$uids) {
                $this->error('参数错误！');
                $uids = implode(',', $uids);
            }
        }

        $map['uid'] = array('in', $uids);
        if (M('member')->where($map)->delete()) {
            M('auth_group_access')->where($map)->delete();
            addlog('删除会员UID：' . $uids);
            $this->success('恭喜，用户删除成功！');
        } else {
            $this->error('参数错误！');
        }
    }

    public function edit()
    {

        $uid = isset($_GET['uid']) ? intval($_GET['uid']) : false;
        if ($uid) {
            //$member = M('member')->where("uid='$uid'")->find();
            $prefix = C('DB_PREFIX');
            $user = M('member');
            $member = $user->field("{$prefix}member.*,{$prefix}auth_group_access.group_id")->join("{$prefix}auth_group_access ON {$prefix}member.uid = {$prefix}auth_group_access.uid")->where("{$prefix}member.uid=$uid")->find();

        } else {
            $this->error('参数错误！');
        }

        $usergroup = M('auth_group')->field('id,title')->select();
        $this->assign('usergroup', $usergroup);

        $this->assign('member', $member);
        $this->display('form');
    }

    public function update($ajax = '')
    {
      if ($ajax == 'yes') {
            $uid = I('get.uid', 0, 'intval');
            $gid = I('get.gid', 0, 'intval');
            M('auth_group_access')->data(array('group_id' => $gid))->where("uid='$uid'")->save();
            die('1');
        }

        $uid = isset($_POST['uid']) ? intval($_POST['uid']) : false;
        $user = isset($_POST['user']) ? htmlspecialchars($_POST['user'], ENT_QUOTES) : '';
        $group_id = isset($_POST['group_id']) ? intval($_POST['group_id']) : 0;
        if (!$group_id) {
            $this->error('请选择用户组！');
        }
        $password = isset($_POST['password']) ? trim($_POST['password']) : false;
        if ($password) {
            $data['password'] = password($password);
        }
        $head = I('post.head', '', 'strip_tags');
        $data['sex'] = isset($_POST['sex']) ? intval($_POST['sex']) : 0;
        $data['head'] = $head ? $head : '/Public/attached/201601/1453389194.png';
        $data['birthday'] = isset($_POST['birthday']) ? strtotime($_POST['birthday']) : 0;
        $data['phone'] = isset($_POST['phone']) ? trim($_POST['phone']) : '';
        $data['qq'] = isset($_POST['qq']) ? trim($_POST['qq']) : '';
        $data['email'] = isset($_POST['email']) ? trim($_POST['email']) : '';
        $data['par_id'] = $_SESSION["uid"];

        $data['t'] = time();
        if (!$uid) {
            if ($user == '') {
                $this->error('用户名称不能为空！');
            }
            if (!$password) {
                $this->error('用户密码不能为空！');
            }
            if (M('member')->where("user='$user'")->count()) {
                $this->error('用户名已被占用！');
            }
            $data['user'] = $user;
            $uid = M('member')->data($data)->add();
            M('auth_group_access')->data(array('group_id' => $group_id, 'uid' => $uid))->add();
            addlog('新增会员，会员UID：' . $uid);
        } else {
        	if($_SESSION["uid"] == 1) {
            	M('auth_group_access')->data(array('group_id' => $group_id))->where("uid=$uid")->save();
        	}
            addlog('编辑会员信息，会员UID：' . $uid);
            M('member')->data($data)->where("uid=$uid")->save();

        }
        $this->success('操作成功！');
    }


    public function add()
    {

        $usergroup = M('auth_group')->field('id,title')->select();
        $this->assign('usergroup', $usergroup);
        $this->display('form');
    }
	
    /**
     * 媒体用户列表
     * */
    public function medialist(){
    	
    	$p = isset($_GET['p']) ? intval($_GET['p']) : '1';
    	$field = isset($_GET['field']) ? $_GET['field'] : '';
    	$keyword = isset($_GET['keyword']) ? htmlentities($_GET['keyword']) : '';
    	$order = isset($_GET['order']) ? $_GET['order'] : 'DESC';
    	$where = '';
    	
    	$prefix = C('DB_PREFIX');
    	if ($order == 'asc') {
    		$order = "{$prefix}member.t asc";
    	} elseif (($order == 'desc')) {
    		$order = "{$prefix}member.t desc";
    	} else {
    		$order = "{$prefix}member.uid asc";
    	}
    	if ($keyword <> '') {
    		if ($field == 'user') {
    			$where = "{$prefix}member.user LIKE '%$keyword%'";
    		}
    		if ($field == 'phone') {
    			$where = "{$prefix}member.phone LIKE '%$keyword%'";
    		}
    		if ($field == 'qq') {
    			$where = "{$prefix}member.qq LIKE '%$keyword%'";
    		}
    		if ($field == 'email') {
    			$where = "{$prefix}member.email LIKE '%$keyword%'";
    		}
    	}
    	if(empty($where)){
    		$where = "{$prefix}member.uid <> {$_SESSION["uid"]}";
    	}
    	else{
    		$where .= " and {$prefix}member.uid <> {$_SESSION["uid"]}";
    	}
    	
    	//查询角色为媒体人的列表
    	if(empty($where)){
    		$where = "{$prefix}auth_group_access.group_id = 10";
    	}
    	else{
    		$where .= " and {$prefix}auth_group_access.group_id = 10";
    	}
    	//echo $where;die;
    	
    	$user = M('member');
    	$pagesize = 10;#每页数量
    	$offset = $pagesize * ($p - 1);//计算记录偏移量
    	$count = $user->field("{$prefix}member.*,{$prefix}auth_group.id as gid,{$prefix}auth_group.title")
    	->order($order)
    	->join("{$prefix}auth_group_access ON {$prefix}member.uid = {$prefix}auth_group_access.uid")
    	->join("{$prefix}auth_group ON {$prefix}auth_group.id = {$prefix}auth_group_access.group_id")
    	->where($where)
    	->count();
	
    	
    	$list = $user->field("{$prefix}member.*,{$prefix}auth_group.id as gid,{$prefix}auth_group.title")
    	->order($order)
    	->join("{$prefix}auth_group_access ON {$prefix}member.uid = {$prefix}auth_group_access.uid")
    	->join("{$prefix}auth_group ON {$prefix}auth_group.id = {$prefix}auth_group_access.group_id")
    	->where($where)
    	->limit($offset . ',' . $pagesize)
    	->select();
    	//$user->getLastSql();die;
    	$page = new \Think\Page($count, $pagesize);
    	$page = $page->show();
    	
    	//不是12月的时候
    	$month = date("m");
    	if($month != "12") {
	    	$begin_date = date("Y-m")."-01 00:00:00";
	    	$next_month = intval($month) + 1;
	    	$end_date = date("Y")."-".$next_month."-01 00:00:00";
    	}
    	else{
    		$begin_date = date("Y-m")."-01 00:00:00";
    		$next_year = intval(date(Y)) + 1;
    		$end_date = $next_year."-01-01 00:00:00";
    	}

    	//统计媒体人本月充值总金额
    	foreach($list as $key=>$item){
    		$rs = D()->query("SELECT sum(money) / 100 as money FROM `qw_order` as a left join `qw_user` as b on a.open_id = b.open_id left join `qw_member` as c on b.proxy_id = c.uid where a.`status` = 1 and a.paytime >= '$begin_date' and a.paytime <= '$end_date' and c.uid = ".$item["uid"]);
    		$list[$key]["money"] = $rs[0]["money"] ? number_format($rs[0]["money"],2) : "0.00";
			
    		for($i = 1; $i <=12; $i++){
    			$index_begin_date = date("Y")."-$i-01 00:00:00";
				if($i < 12)
					$index_end_date = date("Y")."-".($i + 1)."-01 00:00:00";
				else
					$index_end_date = (intval(date("Y")) + 1)."-01-01 00:00:00";
					
    			$rs = D()->query("SELECT sum(money) / 100 as money FROM `qw_order` as a left join `qw_user` as b on a.open_id = b.open_id left join `qw_member` as c on b.proxy_id = c.uid where a.`status` = 1 and a.paytime >= '$index_begin_date' and a.paytime <= '$index_end_date' and c.uid = ".$item["uid"]);
    			$list[$key]["money$i"] = $rs[0]["money"] ? number_format($rs[0]["money"],2) : "0.00";
				//echo D()->getLastSql()."<br>";
    		}			
			//die;
    	}
		
		//print_r($list);die;
    	
    	
    	$this->assign('list', $list);
    	$this->assign('page', $page);
    	$group = M('auth_group')->field('id,title')->select();
    	$this->assign('group', $group);
    	$this->display();
    }	
}
